﻿using Bilibili.Common.Api;
using Bilibili.Model.Common;
using Bilibili.WebClient.Common;
using PCLUntils.Objects;
using System.Text;

namespace Bilibili.WebClient
{
    public sealed class DataInfo
    {
        public DataInfo(string conditions)
        {
            Conditions = conditions;
        }
        public DataInfo(string conditions, string buildVer)
        {
            BuildVer = buildVer;
            Conditions = conditions;
        }
        public DataInfo(string conditions, string buildVer, ApiKeyInfo keyInfo)
        {
            BuildVer = buildVer;
            ApiKeyInfo = keyInfo;
            Conditions = conditions;
        }
        public DataInfo(string conditions, string buildVer, bool msTimeStamp)
        {
            BuildVer = buildVer;
            Conditions = conditions;
            MsTimeStamp = msTimeStamp;
        }
        public DataInfo(string conditions, string buildVer, bool msTimeStamp, ApiKeyInfo keyInfo)
        {
            BuildVer = buildVer;
            Conditions = conditions;
            MsTimeStamp = msTimeStamp;
            ApiKeyInfo = keyInfo;
        }
        public bool MsTimeStamp { get; set; }
        public string Conditions { get; set; }
        public string BuildVer { get; set; } = ApiProviderBase.Build5;
        public ApiKeyInfo ApiKeyInfo { get; set; } = ApiProvider.Instance.AndroidKey;
        public override string ToString()
        {
            StringBuilder stringBuilder = new StringBuilder();
            if (!string.IsNullOrEmpty(Conditions))
            {
                if (Conditions.StartsWith("&"))
                    Conditions = Conditions.Substring(1, Conditions.Length - 1);
                stringBuilder.Append(Conditions);
                stringBuilder.Append("&");
            }
            if (ApiProvider.Instance.AccessKey.IsNotEmpty())
                stringBuilder.Append($"access_key={ApiProvider.Instance.AccessKey}&");
            stringBuilder.Append($"appkey={ApiKeyInfo.Appkey}&build={BuildVer}&platform=android&mobi_app=android");
            if (!MsTimeStamp)
                stringBuilder.Append($"&ts={ApiProvider.Instance.TimeSpanSeconds}");
            else
                stringBuilder.Append($"&ts={ApiProvider.Instance.TimeSpanMilliseconds}");
            var originalData = stringBuilder.ToString();
            return $"{originalData}&sign={ApiProvider.Instance.GetSign(originalData, ApiKeyInfo)}";
        }
    }
}